package com.atguigu.jxc.controller;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.jxc.domain.R;
import com.atguigu.jxc.entity.*;
import com.atguigu.jxc.service.OverflowListService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/overflowListGoods")
public class OverflowListGoodsController {

    @Autowired
    private OverflowListService overflowListService;


    @PostMapping("save")
    public R save(String overflowNumber,
                  @RequestParam("overflowDate") String overflowDate,
                  @RequestParam("remarks") String remarks,
                  @RequestParam("overflowListGoodsStr") String overflowListGoodsStr,
                  HttpSession session){
        //根据session 获取user
        User user = (User) session.getAttribute("currentUser");;
        Integer userId = user.getUserId();


        //封装实体类数据
        OverflowList overflowList = new OverflowList();
        overflowList.setUserId(userId);
        overflowList.setOverflowNumber(overflowNumber);
        overflowList.setOverflowDate(overflowDate);
        overflowList.setRemarks(remarks);

        //解析商品列表
        List<OverflowListGoods> overflowListGoods = JSONObject.parseArray(overflowListGoodsStr, OverflowListGoods.class);
        //封装商品列表
        overflowList.setOverflowListGoodsList(overflowListGoods);


        //开始保存报溢单
        overflowListService.save(overflowList);

        return R.ok(100,"请求成功",null);
    }


    @PostMapping("list")
    public Map<String,Object> list(@RequestParam("sTime") String sTime,
                                   @RequestParam("eTime") String eTime,
                                   HttpSession session){
        Map<String,Object> map = new HashMap<>();

        //遍历这个list
        List<OverflowList> list = overflowListService.getListByDate(sTime, eTime);
        //获取用户名
        User user = (User) session.getAttribute("currentUser");
        String trueName = user.getTrueName();

        //给每一项赋值
        for (OverflowList overflowList : list) {
            overflowList.setTrueName(trueName);
        }

        map.put("rows",list);
        return map;
    }


    @PostMapping("goodsList")
    public Map<String,Object> goodsList(@RequestParam("overflowListId") String overflowListId){
        Map<String,Object> map = new HashMap<>();
        List<OverflowListGoods> listGoods = overflowListService.getByListId(Integer.parseInt(overflowListId));
        map.put("rows",listGoods);
        return map;
    }
}
